/*
 *所有关于Aps_PlantCalendar类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Aps_PlantCalendarService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using DGZImp.ApsProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using DGZImp.ApsProject.IRepositories;
using DGZImp.Core.Exceptions;
using DGZImp.Core.Utilities.Response;
using DGZImp.ApsProject.Dtos;
using DGZImp.Core.EFDbContext;
using SqlSugar;
using DGZImp.Core.DbSqlSugar;
using System.Collections.Generic;

namespace DGZImp.ApsProject.Services
{
    public partial class Aps_PlantCalendarService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IAps_PlantCalendarRepository _repository;//访问数据库
        public ServiceDbContext Db = AutofacContainerModule.GetService<ServiceDbContext>();

        public Aps_MachineCalendarService MachineCalendarService = AutofacContainerModule.GetService<Aps_MachineCalendarService>();

        [ActivatorUtilitiesConstructor]
        public Aps_PlantCalendarService(
            IAps_PlantCalendarRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }


        public async Task<string> GenerateCalendarData(ReqApsCalendarInfo calendarInfo)
        {
            var calendarEntries = new List<Aps_PlantCalendar>();


            DateTime StartTime = Convert.ToDateTime(calendarInfo.StartTime);
            DateTime EndTime = Convert.ToDateTime(calendarInfo.EndTime);



            var list = Db.Set<Aps_Shift>().Where(x => x.ShiftId == calendarInfo.ScheduleId0 || x.ShiftId == calendarInfo.ScheduleId1).ToList();
            if (list.Count == 0)
            {
                throw new ArgumentException("班次信息有误，请检查");
            }

            var hour = Db.Set<Aps_ShiftDetail>()
            .Where(x => x.ClockInType == 1 || x.ClockInType == 3)
            .Where(x => x.ShiftId == calendarInfo.ScheduleId0 || x.ShiftId == calendarInfo.ScheduleId1)
            .GroupBy(x => x.ShiftId)
            .Select(x => new
            {
                ShiftId = x.ShiftId,
                Hours = SqlFunc.AggregateSum(x.Hours)
            }).ToList();


            // 先删除之前的
            await Db.SqlSugarClient.Deleteable<Aps_PlantCalendar>()
                               .Where(x => x.WorkDate >= StartTime && x.WorkDate <= EndTime)
                               .ExecuteCommandAsync();

            for (var date = StartTime; date <= EndTime; date = date.AddDays(1))
            {
                var isRestDay = calendarInfo.Weeks.Contains((int)date.DayOfWeek);

                if (calendarInfo.IsSkip && isRestDay)
                {
                    list.ForEach(i =>
                    {
                        var entry = new Aps_PlantCalendar
                        {
                            WorkDate = date,
                            DateType = "R",


                        };
                        calendarEntries.Add(entry);

                    });
                }
                else
                {
                    list.ForEach(i =>
                    {
                        var entry = new Aps_PlantCalendar
                        {
                            WorkDate = date,
                            DateType = isRestDay ? "R" : "W",
                            // 其他属性可以在这里初始化，例如：
                            ShiftId = i.ShiftId,
                            ShiftType = (int)i.ShiftType,
                            Hours = hour.Where(a => a.ShiftId == i.ShiftId).Select(a => a.Hours).FirstOrDefault(),

                        };
                        calendarEntries.Add(entry);

                    });
                };


            }

            await Db.SqlSugarClient.DoInsertAsync<Aps_PlantCalendar>(calendarEntries);
            // 同步生成设备行事历

            var info = new ReqApsMathineCalendarInfo
            {
                StartTime = calendarInfo.StartTime,
                EndTime = calendarInfo.EndTime
            };
            MachineCalendarService.GenerateMachineCalendarData(info);

            return "OK";
        }
        public async Task<string> GenerateCalendarDataUpdate(ReqApsCalendarInfo calendarInfo)
        {
            var calendarEntries = new List<Aps_PlantCalendar>();

            DateTime StartTime = Convert.ToDateTime(calendarInfo.StartTime);
            DateTime EndTime = Convert.ToDateTime(calendarInfo.EndTime);


            var list = Db.Set<Aps_Shift>().Where(x => x.ShiftId == calendarInfo.ScheduleId0 || x.ShiftId == calendarInfo.ScheduleId1).ToList();
            if (list.Count == 0 && !calendarInfo.IsResult)
            {
                throw new ArgumentException("设置工作日，班次信息必须选择");
            }

            var hour = Db.Set<Aps_ShiftDetail>()
            .Where(x => x.ClockInType == 1 || x.ClockInType == 3)
            .Where(x => x.ShiftId == calendarInfo.ScheduleId0 || x.ShiftId == calendarInfo.ScheduleId1)
            .GroupBy(x => x.ShiftId)
            .Select(x => new
            {
                ShiftId = x.ShiftId,
                Hours = SqlFunc.AggregateSum(x.Hours)
            }).ToList();


            // 先删除之前的
            await Db.SqlSugarClient.Deleteable<Aps_PlantCalendar>()
                              .Where(x => x.WorkDate >= StartTime && x.WorkDate <= EndTime)
                              .ExecuteCommandAsync();

            for (var date = StartTime; date <= EndTime; date = date.AddDays(1))
            {

                if (calendarInfo.IsResult)
                {
                    list.ForEach(i =>
                    {
                        var entry = new Aps_PlantCalendar
                        {
                            WorkDate = date,
                            DateType = "R",


                        };
                        calendarEntries.Add(entry);

                    });
                }
                else
                {
                    list.ForEach(i =>
                    {
                        var entry = new Aps_PlantCalendar
                        {
                            WorkDate = date,
                            DateType = "W",
                            // 其他属性可以在这里初始化，例如：
                            ShiftId = i.ShiftId,
                            ShiftType = (int)i.ShiftType,
                            Hours = hour.Where(a => a.ShiftId == i.ShiftId).Select(a => a.Hours).FirstOrDefault(),

                        };
                        calendarEntries.Add(entry);

                    });
                };


            }

            await Db.SqlSugarClient.DoInsertAsync<Aps_PlantCalendar>(calendarEntries);
            return "OK";
        }
        public async Task<List<ResLeanApsLineCalendarInfo>> GetList(string time)
        {
            if (string.IsNullOrEmpty(time))
                throw new AppException("请选择年月");

            DateTime date = Convert.ToDateTime(time);
            DateTime begin = Convert.ToDateTime(date.Year + "-" + date.Month + "-01");
            DateTime end = begin.AddMonths(1).AddDays(-1);

            //var list = Db.Set<LeanBasePlantCalendar, LeanApsLineCalendar, LeanBaseForeman, LeanBaseSchedule>()
            var list = await Db.Set<Aps_PlantCalendar>()
                .LeftJoin<Aps_Shift>((a, b) => a.ShiftId == b.ShiftId && b.IsValid == 1)
                .OrderBy((a, b) => a.WorkDate)
                .Where((a, b) => a.WorkDate >= begin && a.WorkDate <= end)
                .Select((a, b) => new ResLeanApsLineCalendarInfo
                {
                    PlantCalendarId = a.PlantCalendarId.SelectAll(),
                    ShiftCode = b.ShiftCode,
                    ShiftName = b.ShiftName

                }).ToListAsync();

            return list;
        }

        public async Task<string> UpdateShift(long? ShiftId, long? PlantCalendarId)
        {
            var info = Db.Set<Aps_PlantCalendar>().Where(a => a.PlantCalendarId == PlantCalendarId).FirstOrDefault();

            if (ShiftId != null)
            {
                var hour = await Db.Set<Aps_ShiftDetail>()
                  .Where(x => x.ClockInType == 1 || x.ClockInType == 3)
                  .Where(x => x.ShiftId == ShiftId)
                  .GroupBy(x => x.ShiftId)
                  .Select(x => new
                  {
                      ShiftId = x.ShiftId,
                      Hours = SqlFunc.AggregateSum(x.Hours)
                  }).ToListAsync();
                info.ShiftId = (long)ShiftId;
                info.Hours = hour.Where(a => a.ShiftId == ShiftId).Select(a => a.Hours).FirstOrDefault();
            }
            else
            {
                info.ShiftId = null;
                info.Hours = null;
            }

            await Db.SqlSugarClient.DoUpdateAsync<Aps_PlantCalendar>(info, x => x.PlantCalendarId == PlantCalendarId);

            return "修改成功";

        }
    }
}
